import theme from '@/theme';
import classNames from 'classnames';
import { memo, useState } from 'react';
import { Text, View } from '@tarojs/components';
import { Icon } from 'pd-taro-ui';
import './index.scss';
import type { CascaderProps } from './index';
import { pxTransform } from '@tarojs/taro';

interface CascaderItemProps {
  item: any;
  labelField: string;
  valueField: string;
  getIsCheck: (item: any) => boolean;
  toggleCheck: (item: any, deepth: number) => any;
  toNextDeepth: (item: any, deepth: number) => any;
  deepth: number;
  isCheckBox?: boolean;
}
const CascaderItem = memo(
  ({ getIsCheck, item, labelField, valueField, toggleCheck, toNextDeepth, deepth, isCheckBox = false }: CascaderItemProps) => {
    const hadValue = !!item[valueField] || typeof item[valueField] === 'number';
    const disabled = item.disabled || !hadValue;
    const checked = getIsCheck(item);
    const hadChildren = !!item.children?.length;
    return (
      <View
        className={classNames({
          'pd-cascader__item': true,
          'pd-cascader__item--checked': checked,
          'pd-cascader__item--disabled': disabled,
        })}
        onClick={e => {
          e?.stopPropagation?.();
          if (!isCheckBox || !hadChildren) {
            toggleCheck(item, deepth);
          } else {
            toNextDeepth(item, deepth);
          }
        }}
        hoverStyle={{
          opacity: 0.7,
        }}>
        {isCheckBox && (
          <Icon
            size={40}
            name={checked ? 'Checked' : 'Unchecked'}
            color={checked ? theme.primaryColor : '#bbb'}
            onClick={e => {
              e?.stopPropagation?.();
              toggleCheck(item, deepth);
            }}
            style={{
              marginRight: pxTransform(10),
            }}
          />
        )}
        <Text className={classNames('pd-cascader__item__text', { 'pd-cascader__item__text--disabled': disabled })}>{item[labelField]}</Text>
        {!isCheckBox && checked && <Icon size={40} name='selected' color={theme.primaryColor} />}
        {hadChildren && <Icon size={40} name='right' color='#bbb' />}
      </View>
    );
  },
);
export default CascaderItem;
